package com.huanxun.fragment;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

//import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huanxun.bean.MsgListBean;
import com.huanxun.bean.MsgListBean.Content;
import com.huanxun.foodspath3.MessageActivity;
import com.huanxun.foodspath3.MsgDetail;
import com.huanxun.foodspath3.MsgDetail_buyer;
import com.huanxun.foodspath3.R;
import com.huanxun.utils.Constants;
import com.huanxun.utils.MLogger;
import com.huanxun.utils.NetConnectiveUils;
import com.huanxun.utils.SystemUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

/**
 * 消息列表Fragment
 * 
 */
public class MsgListFragment extends Fragment {
	private View v;
	private PullToRefreshListView lv;
	static final int MENU_MANUAL_REFRESH = 0;
	static final int MENU_DISABLE_SCROLL = 1;
	static final int MENU_SET_MODE = 2;
	static final int MENU_DEMO = 3;

	private List<Content> list;
	private com.huanxun.fragment.MsgListFragment.mAdapter mAdapter;
	private ListView actualListView;

	private MsgListBean msgListBean;
	Context context;
	private String id;

	private int increasePageNumber = 1;
	private String path = "http://112.126.80.199:9990/foodspath/v01/message/list?pageNumber="
			+ increasePageNumber + "&userId=";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		v = inflater.inflate(R.layout.fragment_message, null);
		MessageActivity activity2 = (MessageActivity) getActivity();
		id = activity2.id;
		MLogger.i("Userid", id);
		LoadMsgData();
		return v;
	}

	private void LoadMsgData() {
		SystemUtils.httpUtils.send(HttpMethod.GET, Constants.URL_MSG_LIST + id,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						String json = responseInfo.result;
						MLogger.i("MsgList", json);
						processJson(json);

					}

					@Override
					public void onFailure(HttpException error, String msg) {
					}
				});
	}

	protected void processJson(String Json) {
		msgListBean = SystemUtils.gson.fromJson(Json, MsgListBean.class);
		list = msgListBean.data.content;
		initView();
	}

	private void initView() {
		lv = (PullToRefreshListView) v.findViewById(R.id.lv_msg);
		/**
		 * 实现 接口 OnRefreshListener2<ListView> 以便与监听 滚动条到顶部和到底部
		 */
		lv.setOnRefreshListener(new OnRefreshListener2<ListView>() {
			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				String formatSystemTime = SystemUtils.formatSystemTime();
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(
						"最后更新时间:" + formatSystemTime);
				new GetDataTask().execute(path + id);
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				new GetDataTask().execute(path + id);
			}
		});

		// 设置PullRefreshListView上提加载时的加载提示
		lv.setMode(Mode.BOTH);
		lv.getLoadingLayoutProxy(false, true).setPullLabel("上拉加载...");
		lv.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载...");
		lv.getLoadingLayoutProxy(false, true).setReleaseLabel("松开加载更多...");

		// 设置PullRefreshListView下拉加载时的加载提示
		lv.getLoadingLayoutProxy(true, false).setPullLabel("下拉刷新...");
		lv.getLoadingLayoutProxy(true, false).setRefreshingLabel("正在加载...");
		lv.getLoadingLayoutProxy(true, false).setReleaseLabel("松开加载更多...");
		actualListView = lv.getRefreshableView();
		actualListView.setTextFilterEnabled(true);
		actualListView.setDivider(new ColorDrawable(Color.BLACK));
		actualListView.setDividerHeight(1);
		// Need to use the Actual ListView when registering for Context Menu
		registerForContextMenu(actualListView);

		mAdapter = new mAdapter(list);
		actualListView.setAdapter(mAdapter);
		lv.setOnItemClickListener(new ItemClickListener());

	}

	private class mAdapter extends BaseAdapter {
		private List<Content> list;

		public mAdapter(List<Content> list) {
			super();
			this.list = list;
		}

		@Override
		public int getCount() {

			return list.size();
		}

		@Override
		public Object getItem(int position) {

			return list.get(position);
		}

		@Override
		public long getItemId(int position) {

			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = null;
			ViewHolder holder = null;
			if (convertView == null) {
				v = View.inflate(context, R.layout.item_lv_title, null);
				holder = new ViewHolder();
				holder.point = v.findViewById(R.id.point);
				holder.title = (TextView) v.findViewById(R.id.title);
				holder.date = (TextView) v.findViewById(R.id.date);
				holder.desc = (TextView) v.findViewById(R.id.desc);
				v.setTag(holder);
			} else {
				v = convertView;
				holder = (ViewHolder) v.getTag();
			}
			Content info = list.get(position);
			String status = info.status;
			if ("0".equals(status)) {
				holder.point.setVisibility(View.VISIBLE);
			} else {
				holder.point.setVisibility(View.GONE);
			}

			holder.title.setText(info.title);
			String time = SystemUtils.changeTimeFormat(info.createAt);
			holder.date.setText(time);
			holder.desc.setText(info.content);
			return v;
		}

	}

	static class ViewHolder {
		View point;
		TextView title;
		TextView date;
		TextView desc;
	}

	// 模拟网络加载数据的 异步请求类
	//
	private class GetDataTask extends AsyncTask<String, Void, String> {

		// 子线程请求数据
		@Override
		protected String doInBackground(String... params) {
			String url = params[0];
			String response = "";
			DefaultHttpClient client = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(url);
			try {
				HttpResponse execute = client.execute(httpGet);
				InputStream content = execute.getEntity().getContent();

				BufferedReader buffer = new BufferedReader(
						new InputStreamReader(content));
				String s = "";
				while ((s = buffer.readLine()) != null) {
					response += s;
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return response;
		}

		// 主线程更新UI
		@Override
		protected void onPostExecute(String result) {
			// 向RefreshListView Item 添加一行数据 并刷新ListView
			// mListItems.addLast("Added after refresh	...");
			if(NetConnectiveUils.isNetworkAvailable((Activity)context)){
			String json = result;
			MsgListBean fromJson = SystemUtils.gson.fromJson(json,
					MsgListBean.class);
			if (fromJson.data.numberOfElements <= 10
					&& fromJson.data.numberOfElements > 0) {
				increasePageNumber++;
				path = "http://112.126.80.199:9990/foodspath/v01/message/list?pageNumber="
						+ increasePageNumber + "&userId=";
				Toast.makeText((MessageActivity) getActivity(), "更新数据",
						Toast.LENGTH_SHORT).show();
				// 通知RefreshListView 我们已经更新完成
				// Call onRefreshComplete when the list has been refreshed.

				for (int i = 0; i < fromJson.data.numberOfElements; i++) {
					Content content = fromJson.data.content.get(i);
					list.add(list.size(), new MsgListBean.Content(
							content.content, content.createAt, content.title,
							content.fromId, content.id, content.orderId,
							content.status, content.toId));

				}
			} else {
				SystemUtils.toast(context, "没有更多的数据可以加载╮(╯▽╰)╭");
			}
			mAdapter.notifyDataSetChanged();
			lv.onRefreshComplete();
			}else{
				FragmentManager fragmentManager = getFragmentManager();
				FragmentTransaction beginTransaction = fragmentManager.beginTransaction();
				beginTransaction.replace(R.id.fl_msg, new NetConnectiveFailedFragment()).commit();
				beginTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
			
			}
			super.onPostExecute(result);

		}
	}

	private class ItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view,
				final int position, long id) {
			View point = view.findViewById(R.id.point);
			Content content = mAdapter.list.get(position - 1);
			MLogger.i("Msg_Position", position + "");
			String changeTimeFormat = SystemUtils
					.changeTimeFormat(content.createAt);
			String strID = content.id;
			content.status = "1";
			mAdapter.notifyDataSetChanged();
			point.setVisibility(View.GONE);
			SystemUtils.httpUtils.send(HttpMethod.POST,
					Constants.URL_MSG_ISREADED + strID + "/status/1",
					new RequestCallBack<String>() {

						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							String result = responseInfo.result;
							MLogger.i("Msg_Setreaded", result);
						}

						@Override
						public void onFailure(HttpException error, String msg) {
							MLogger.i("Msg_Setreaded", "lose");
						}
					});
			Intent intent;
			MessageActivity activity = (MessageActivity) getActivity();
			String roleNumber = activity.roleNumber;

			if (NetConnectiveUils.isNetworkAvailable(activity)) {
				if ("2".equals(roleNumber)) {
					intent = new Intent(context, MsgDetail_buyer.class);
				} else {
					intent = new Intent(context, MsgDetail.class);
				}

				intent.putExtra("title", content.title);
				intent.putExtra("id", content.id);
				intent.putExtra("time", changeTimeFormat);
				intent.putExtra("position", position);
				startActivity(intent);
			} else {
				SystemUtils.toast(activity, "请检查网络");
			}

		}
	}

	@Override
	public void onAttach(Activity activity) {
		this.context = activity;
		super.onAttach(activity);
	}

}
